package com.g13.virtualpethospital.controller;

import com.g13.virtualpethospital.common.Result;
import com.g13.virtualpethospital.controller.request.UploadAnswerRequest;
import com.g13.virtualpethospital.controller.response.ExamDetailResponse;
import com.g13.virtualpethospital.controller.response.UploadAnswerResponse;
import com.g13.virtualpethospital.controller.response.UploadAnswerResponseExam;
import com.g13.virtualpethospital.entity.QuestionEntity;
import com.g13.virtualpethospital.entity.TestExamEntity;
import com.g13.virtualpethospital.entity.TestPaperBriefEntity;
import com.g13.virtualpethospital.entity.TestPaperEntity;
import com.g13.virtualpethospital.entity.base.AnswerResult;
import com.g13.virtualpethospital.entity.base.AnswerResultExam;
import com.g13.virtualpethospital.exceptions.TestExamException;
import com.g13.virtualpethospital.exceptions.TestPaperException;
import com.g13.virtualpethospital.service.Implement.TestExamServiceImpl;
import com.g13.virtualpethospital.service.QuestionService;
import com.g13.virtualpethospital.service.TestExamService;
import com.g13.virtualpethospital.service.TestPaperService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Title: TestExamController
 * @Author chilly
 * @Package com.g13.virtualpethospital.controller
 * @Date 2024/4/17 13:16
 * @description: 考试记录相关接口
 */
@Slf4j
@RestController
@ApiModel("试卷操作相关接口")
@RequestMapping("/exam")
public class TestExamController {
    @Autowired
    private TestExamService testExamService;
    @Autowired
    private TestPaperService testPaperService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private TestPaperController testPaperController;
    @PostMapping("/addExam")
    @ApiOperation("添加考试记录")
    public Result<Integer> addTestExam(@RequestBody TestExamEntity testExam) {
        TestExamEntity addtestExamEntity = new TestExamEntity();
        addtestExamEntity.setUserId(testExam.getUserId());
        addtestExamEntity.setTestId(testExam.getTestId());
        addtestExamEntity.setScore(testExam.getScore());
        addtestExamEntity.setAnswers(testExam.getAnswers());
        try {
            testExamService.addTestExam(addtestExamEntity);
            return Result.success("添加成功", null);
        } catch (Exception e) {
            return Result.fail("添加失败" + e.getMessage());
        }
    }

    @GetMapping("/showAllExam")
    @ApiOperation("显示用户所有考试记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", required = true, paramType = "query", dataType = "String")
    })
    public Result<List<Map<String,String>>> findAllExam(@NonNull @RequestParam ("userId") String userId){
        try {
            List<TestExamEntity> res = testExamService.findTestExamByUserId(userId);
            List<Map<String, String>> examList = new ArrayList<>();

            for (TestExamEntity paper : res) {
                Map<String, String> paperInfo = new HashMap<>();
                    List<TestPaperBriefEntity> paperBriefEntity = testPaperService.findTestPaperById(paper.getTestId());
                    if (paperBriefEntity.isEmpty()){
                        paperInfo.put("headline","不存在或已经被删除");
                        paperInfo.put("testExamId",null);
                        paperInfo.put("score",null);
                        paperInfo.put("testId",null);
                        examList.add(paperInfo);
                    }
                    else {
                        TestPaperBriefEntity paperEntity = paperBriefEntity.get(0);
                        paperInfo.put("headline", paperEntity.getHeadline());
                        paperInfo.put("testExamId", String.valueOf(paper.getTestExamId()));
                        paperInfo.put("score", String.valueOf(paper.getScore()));
                        paperInfo.put("testId", String.valueOf(paper.getTestId()));
                        examList.add(paperInfo);
                    }
                }
            if (res.isEmpty()) {
                return Result.fail("没有找到考试记录", Collections.emptyList());
            } else {
                return Result.success("查询成功", examList);
            }
        } catch (Exception e) {
            return Result.fail("显示考试记录失败" + e.getMessage(), null);
        }
    }


    @GetMapping("/chooseExam")
    @ApiOperation("选择考试记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "testExamId", value = "考试记录Id", required = true, paramType = "query", dataType = "String")
    })
    public Result<ExamDetailResponse> chooseExam(@NonNull @RequestParam("testExamId") String testExamId) {
        try {
            List<TestExamEntity> testExamEntities = testExamService.findTestExamById(testExamId);
            List<AnswerResultExam> correctionResults = new ArrayList<>();
            if (testExamEntities.isEmpty()) {
                return Result.fail("考试记录不存在");
            }
            TestExamEntity testExam = testExamEntities.get(0);
            List<TestPaperBriefEntity> resList = testPaperService.findTestPaperById(testExam.getTestId());

                TestPaperBriefEntity res = resList.get(0);
                TestPaperEntity testPaperEntity = new TestPaperEntity();
                testPaperEntity.setHeadline(res.getHeadline());
                testPaperEntity.setPaperId(res.getPaperId());
                testPaperEntity.setTotalScore(res.getTotalScore());
                testPaperEntity.setTime(res.getTime());
                testPaperEntity.setScores(res.getScores());

                List<QuestionEntity> questions = new ArrayList<>();
                for (String questionId : res.getQuestions()) {
                    QuestionEntity questionEntity = questionService.findQuestionById(questionId);
                    questions.add(questionEntity);
                }
                testPaperEntity.setQuestions(questions.toArray(new QuestionEntity[0]));


                List<String> questionIds = questionService.findQuestionIdsByPaperId(testExam.getTestId());
                List<String> selectedOptions = testExam.getAnswers();
                int totalscore = 0;
                for (int i = 0; i < questionIds.size(); i++) {
                    String questionId = questionIds.get(i);
                    String selectedOption = selectedOptions.get(i);
                    if(selectedOption == null)
                        selectedOption = "EMPTY";
                    String correctOption = questionService.findCorrectOptionByQuestionId(questionId);

                    boolean correct = selectedOption.equals(correctOption);
                    if(correct) {
                        totalscore = totalscore + 5;
                    }

                    AnswerResultExam correctionResult = AnswerResultExam.builder()
                            .correct(correct)
                            .correctOption(correctOption)
                            .selectedOption(selectedOption)
                            .build();

                    correctionResults.add(correctionResult);
                }
                UploadAnswerResponseExam uploadAnswerResponse = new UploadAnswerResponseExam();
                uploadAnswerResponse.setTotalScore(totalscore);
                uploadAnswerResponse.setCorrectionResults(correctionResults);

            ExamDetailResponse examDetailResponse = new ExamDetailResponse();

            examDetailResponse.setTestPaperEntity(testPaperEntity);
            examDetailResponse.setUploadAnswerResponse(uploadAnswerResponse);

            return Result.success("选择考试记录成功", examDetailResponse);
        } catch (Exception e) {
            return Result.fail("选择考试记录失败：" + e.getMessage(), null);
        }





//        try {
//            UploadAnswerRequest uploadAnswerRequest = new UploadAnswerRequest();
//            List<TestExamEntity> testExamEntity = testExamService.findTestExamById(testExamId);
//            TestExamEntity testExam = testExamEntity.get(0);
//            uploadAnswerRequest.setPaperId(testExam.getTestId());
//            uploadAnswerRequest.setSelectedOptions(testExam.getAnswers());
//
//            return testPaperController.uploadAnswers(uploadAnswerRequest);
//
//        }catch(Exception e){
//            return Result.fail("查询失败", null);

    }


    /**
     * 删除考试记录
     * @param testExamId
     * @return
     */
    @DeleteMapping("/deleteExam")
    @ApiOperation("删除考试记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "testExamId", value = "考试记录编号", required = true, paramType = "query", dataType = "String")})
    public Result<Integer> deleteTestPaper(@NonNull @RequestParam("testExamId")  String testExamId) {
        try {
            testExamService.deleteTestExam(testExamId);
            return Result.success("删除成功", null);
        } catch (Exception e) {
            return Result.fail("试卷记录不存在，删除失败");
        }
    }
}
//        try {
//            List<TestExamEntity> resList = testExamService.findTestExamById(testExamId);
//            List<AnswerResult> correctionResults = new ArrayList<>();
//            if (!resList.isEmpty()) {
//                TestExamEntity res = resList.get(0);
//                TestExamEntity testExamEntity = new TestExamEntity();
//                testExamEntity.setTestExamId(res.getTestExamId());
//                testExamEntity.setAnswers(res.getAnswers());
//                testExamEntity.setTestId(res.getTestId());
//                testExamEntity.setUserId(res.getUserId());
//                testExamEntity.setScore(res.getScore());
//
//                List<String> questionIds = questionService.findQuestionIdsByPaperId(testExamEntity.getTestId());
//                List<String> selectedOptions = testExamEntity.getAnswers();
//                for (int i = 0; i < questionIds.size(); i++) {
//                    String questionId = questionIds.get(i);
//                    String selectedOption = selectedOptions.get(i);
//                    if(selectedOption == null)
//                        selectedOption = "EMPTY";
//                    String correctOption = questionService.findCorrectOptionByQuestionId(questionId);
//
//                    boolean correct = selectedOption.equals(correctOption);
//
//                    AnswerResult correctionResult = AnswerResult.builder()
//                            .correct(correct)
//                            .correctOption(correctOption)
//                            .build();
//
//                    correctionResults.add(correctionResult);
//                }
//                UploadAnswerResponse uploadAnswerResponse = new UploadAnswerResponse();
//                uploadAnswerResponse.setTotalScore(testExamEntity.getScore());
//                uploadAnswerResponse.setCorrectionResults(correctionResults);
//
//
//                return Result.success("选择记录成功", uploadAnswerResponse);
//            } else {
//                return Result.fail("记录不存在", null);
//            }
//        } catch (Exception e) {
//            return Result.fail("选择失败" + e.getMessage(), null);
//        }